import React, { useState, useEffect } from "react";
import { Layout, Spin, Empty, Alert } from "antd";
import { useAppDispatch, useAppSelector } from "../../hooks/redux";
import { fetchProjects } from "../../store/projectSlice";
import ProjectHeader from "./components/ProjectHeader";
import ProjectFilters from "./components/ProjectFilters";
import ProjectBoard from "./components/ProjectBoard";

const { Content } = Layout;

/**
 * 项目管理主页面组件
 * 支持多项目展示，每个项目都有独立的任务看板
 *
 * 功能特性：
 * - 支持"我创建的"和"我参与的"项目视图切换
 * - 项目级别的筛选功能（项目状态、创建时间等）
 * - 每个项目内嵌任务筛选和排序功能
 * - 支持项目的创建、编辑、删除
 * - 拖拽式任务看板，支持跨分组移动任务
 */
const ProjectManagement: React.FC = () => {
  const dispatch = useAppDispatch();
  const { projects, loading, error } = useAppSelector(state => state.project);

  // 项目筛选和排序状态
  const [projectFilters, setProjectFilters] = useState({
    search: "",
    status: [] as string[],
    createdDate: undefined as any
  });
  //筛选 导致 projectFilters 变化 然后 函数组件重新执行 getFilteredAndSortedProjects 函数也会重新执行

  const [projectSort, setProjectSort] = useState({
    field: "updatedAt",
    order: "desc" as "asc" | "desc"
  });

  useEffect(() => {
    dispatch(fetchProjects());
  }, [dispatch]);

  // 筛选和排序项目
  const getFilteredAndSortedProjects = () => {
    let filteredProjects = projects.filter(project => {
      // 搜索筛选
      const matchesSearch =
        !projectFilters.search ||
        project.title.toLowerCase().includes(projectFilters.search.toLowerCase()) ||
        (project.description || "").toLowerCase().includes(projectFilters.search.toLowerCase());

      // 状态筛选（这里可以根据项目任务状态来判断项目状态）
      const matchesStatus = projectFilters.status.length === 0 || projectFilters.status.includes("active");

      // 创建时间筛选
      const matchesCreatedDate =
        !projectFilters.createdDate ||
        (new Date(project.createdAt) >= projectFilters.createdDate[0] &&
          new Date(project.createdAt) <= projectFilters.createdDate[1]);

      return matchesSearch && matchesStatus && matchesCreatedDate;
    });

    // 排序
    filteredProjects.sort((a, b) => {
      const aValue = a[projectSort.field as keyof typeof a];
      const bValue = b[projectSort.field as keyof typeof b];

      if (aValue == null) return 1;
      if (bValue == null) return -1;

      let comparison = 0;
      if (typeof aValue === "string" && typeof bValue === "string") {
        comparison = aValue.localeCompare(bValue);
      } else if (typeof aValue === "number" && typeof bValue === "number") {
        comparison = aValue - bValue;
      } else if (aValue instanceof Date && bValue instanceof Date) {
        comparison = aValue.getTime() - bValue.getTime();
      } else {
        comparison = String(aValue).localeCompare(String(bValue));
      }

      return projectSort.order === "desc" ? -comparison : comparison;
    });

    return filteredProjects;
  };

  const filteredProjects = getFilteredAndSortedProjects();

  if (loading) {
    return (
      <Layout className="min-h-screen bg-gray-50">
        <Content className="p-6 flex items-center justify-center">
          <Spin size="large" />
        </Content>
      </Layout>
    );
  }

  if (error) {
    return (
      <Layout className="min-h-screen bg-gray-50">
        <Content className="p-6">
          <Alert message="加载失败" description={error} type="error" showIcon />
        </Content>
      </Layout>
    );
  }

  return (
    <Layout className="min-h-screen bg-gray-50">
      <Content className="p-6">
        <div className="max-w-full mx-auto">
          {/* 页面头部：标题、视图切换、新建项目按钮 */}
          <ProjectHeader />

          {/* 项目筛选器 */}
          <ProjectFilters
            filters={projectFilters}
            sort={projectSort}
            onFiltersChange={setProjectFilters}
            onSortChange={setProjectSort}
          />

          {/* 项目看板列表 */}
          {filteredProjects.length === 0 ? (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-12">
              <Empty
                description={projects.length === 0 ? "暂无项目数据，快来创建第一个项目吧！" : "没有符合筛选条件的项目"}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            </div>
          ) : (
            <div className="space-y-6">
              {filteredProjects.map(project => (
                <ProjectBoard key={project.id} project={project} />
              ))}
            </div>
          )}
        </div>
      </Content>
    </Layout>
  );
};

export default ProjectManagement;
